package work.chenxr.security.user;

import org.apache.commons.lang3.ObjectUtils;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 * @Author Chenxr
 * @Date 2023/10/23
 * @Description 当前用户工具类
 */
public class SecurityUser {
    /**
     * 获取用户信息
     */
    public static UserDetail getUser() {
        UserDetail user;
        try {
            user = (UserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        } catch (Exception e) {
            return null;
        }
        return user;
    }

    /**
     * 获取用户ID
     */
    public static Long getUserId() {
        UserDetail user = getUser();
        if (ObjectUtils.isEmpty(user)) {
            return null;
        }
        return user.getId();
    }
}
